package com.jd.ty.web.util;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

public class DateConverter extends StrutsTypeConverter {

	private static String DATE_TIME_FOMART = "yyyy-MM-dd HH:mm:ss";

	private static String DATE_FOMART = "yyyy-MM-dd";

	@Override
	public Object convertFromString(Map context, String[] values, Class clazz) {

		Date date = null;

		String dateString = null;

		if (values != null && values.length > 0) {

			dateString = values[0];

			if (dateString != null) {

				SimpleDateFormat format = new SimpleDateFormat(DATE_FOMART);

				try {

					date = format.parse(dateString);

				} catch (ParseException e) {

					date = null;

				}

				if (date == null) {

					format = new SimpleDateFormat(DATE_TIME_FOMART);

					try {

						date = format.parse(dateString);

					} catch (ParseException e) {

						date = null;

					}

				}

			}

		}

		return date;

	}

	@Override
	public String convertToString(Map arg0, Object obj) {

        if (obj instanceof Date) {   
            SimpleDateFormat format = new SimpleDateFormat(DATE_FOMART);   
            try {   
                return format.format((Date)obj);   
            } catch (RuntimeException e) {   
                return "";   
            }   
        }   
        return "";   

	}

}
